package com.maodou.core.datastore

import android.content.Context
import com.maodou.core.datastore.db.DatabaseProvider
import com.maodou.core.datastore.db.ListCacheStore
import com.maodou.core.datastore.db.ObjectCacheStore
import com.maodou.core.datastore.storage.KeyValueStorage
import com.maodou.core.datastore.storage.MmkvKeyValueStorage
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory

class DataStore(
    val keyValue: KeyValueStorage,
    val listCache: ListCacheStore,
    val objectCache: ObjectCacheStore,
) {
    companion object {
        @JvmStatic
        fun create(context: Context, moshi: Moshi? = null): DataStore {
            val effectiveMoshi = moshi ?: Moshi.Builder()
                .add(KotlinJsonAdapterFactory())
                .build()
            val db = DatabaseProvider.get(context)
            val listCache = ListCacheStore(db.cacheDao(), effectiveMoshi)
            val objectCache = ObjectCacheStore(db.cacheDao(), effectiveMoshi)
            val kv = MmkvKeyValueStorage.create(context, effectiveMoshi)
            return DataStore(kv, listCache, objectCache)
        }
    }
}